﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;
using BigTestV3.common;
using BigTestV3.xmlHelp;
using ICSharpCode.SharpZipLib.Zip;

namespace BigTestV3
{
    public partial class frmUpload : Form
    {
        public frmUpload()
        {
            InitializeComponent();
        }

        private BasicSetting setting = null;

        /// <summary>
        /// 初始化窗体并 加载数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UploadLoad(object sender, EventArgs e)
        {
            string path = FilePathTotal.PathPath;
            if (File.Exists(path))
            {
                FilePath filePath = XmlHelper.XmlDeserializeFromFile<FilePath>(path, Encoding.UTF8);
                if (File.Exists(filePath.Path))
                {
                    setting = XmlHelper.XmlDeserializeFromFile<BasicSetting>(filePath.Path, Encoding.UTF8);

                    List<string> temp = Directory.GetFiles(setting.TecPath).ToList();
                    List<StuAns> stuAnses = new List<StuAns>();


                    foreach (var str in temp)
                    {
                        StuAns stuAns = new StuAns();
                        stuAns.Name = Path.GetFileNameWithoutExtension(str);
                        stuAnses.Add(stuAns);

                    }
                    //dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
                    
                    dataGridView1.DataSource = stuAnses;
                    dataGridView1.Columns[0].Width = 200;

                }
            }
            else
            {
                MessageBox.Show("文件不存在");
            }

        }

        /// <summary>
        /// 上传事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UploadClick(object sender, EventArgs e)
        {
            string path = FilePathTotal.BigTestInfo;
            List<XmlTestPlaceStu> student = null;
            BigTestInfo papers = null;
            if (File.Exists(path))
            {
                papers = XmlHelper.XmlDeserializeFromFile<BigTestInfo>(path, Encoding.UTF8);
            }
            string name = papers.TestTest.TestID + "_" + papers.TestPaper.PapersID + "_" + DateTime.Now.ToShortDateString().Replace("/", "");
            ZipFile(name+".zip");
            if (File.Exists(setting.TecPath + "\\"+name+".zip"))
            {
                UploadFtp(setting.TecPath,name,FilePathTotal.UploadUrl,null,null);
            }
        }

        /// <summary>
        /// 压缩文件(多个)
        /// </summary>
        public void ZipFile(string name)
        {
            List<string> strPath = GetFilePath();
            if (File.Exists(FilePathTotal.AnswerInfoPath))
            {
                AnswerInfo info =
                    xmlHelp.XmlHelper.XmlDeserializeFromFile<AnswerInfo>(
                        FilePathTotal.AnswerInfoPath, Encoding.UTF8);
            }
            FileInfo zipFile = new FileInfo(setting.TecPath+"\\"+name);
            ZipOutputStream zipOut = null; 
            zipOut = new ZipOutputStream(zipFile.Create());     

            for (int i = 0; i < strPath.Count; i++)
            {
                FileInfo file = new FileInfo(strPath[i]); 
                if (file.Exists == false)
                {
                    MessageBox.Show("要压缩的文件(" + strPath[i] + ")不存在");
                    continue;
                }
                zipOut.PutNextEntry(new ZipEntry(file.Name)); 
                zipOut.SetComment("这里是注释");    

                FileStream fs = file.OpenRead(); 
                long dataLengthToRead = fs.Length;                          
                while (dataLengthToRead > 0)
                {
                    
                    byte[] buffer = new byte[524288];
                    int lengthRead = fs.Read(buffer, 0, buffer.Length); 
                    zipOut.Write(buffer, 0, lengthRead);                 
                    dataLengthToRead = dataLengthToRead - lengthRead;
                }
                fs.Close();  
            }

            zipOut.Finish();         
            zipOut.Close();
        }

        /// <summary>
        /// 获取压缩的文件目录
        /// </summary>
        /// <returns></returns>
        private  List<string> GetFilePath()
        {
            if (setting != null)
            {
                return Directory.GetFiles(setting.TecPath).ToList();
            }
            return null;

        }

        public static int UploadFtp(string filePath, string filename, string ftpServerIP, string ftpUserID, string ftpPassword)
        {
            FileInfo fileInf = new FileInfo(filePath + "\\" + filename+".zip");
            string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
            FtpWebRequest reqFTP;
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileInf.Name+".zip"));
            try
            {
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

                
                reqFTP.KeepAlive = false;

                reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
 
                reqFTP.UseBinary = true;

                reqFTP.ContentLength = fileInf.Length;

                int buffLength = 2048;
                byte[] buff = new byte[buffLength];
                int contentLen;

               
                FileStream fs = fileInf.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

                Stream strm = reqFTP.GetRequestStream();

                contentLen = fs.Read(buff, 0, buffLength);
          
                while (contentLen != 0)
                {
                   
                    strm.Write(buff, 0, contentLen);
                    contentLen = fs.Read(buff, 0, buffLength);
                }             
                strm.Close();
                fs.Close();
                return 0;
            }
            catch (Exception ex)
            {
                reqFTP.Abort();
                MessageBox.Show(ex.Message);
               
                return -2;
            }
        }

        private void ImportToDataBase(object sender, EventArgs e)
        {
            Answer answer = XmlHelper.XmlDeserializeFromFile<Answer>(@"D:\Answer\12013051053.xml", Encoding.UTF8);
            int stutestid = 0;
               using(var context=new languageEntities1())
               {
                   int temptestId = Convert.ToInt32(answer.TestId);
                   StudentTest test = context.StudentTest.Where(
                       s => s.StudentID == answer.StudentId && s.TestID == temptestId).FirstOrDefault();

                   stutestid = test.StudentTestID;

                   List<StudentTestDetail> list = context.StudentTestDetail.Where(td => td.StudentTestID == stutestid).ToList();

                   decimal scores = 0;

                   foreach (StudentTestDetail d in list)
                   {
                       foreach (TestDetail sd in answer.List)
                       {
                           if (d.TestLibraryID == Convert.ToInt32(sd.TestLibraryId) && d.PapersDetailID == Convert.ToInt32(sd.PapersDetailId))
                           {
                               d.TotalScores = sd.TotalScores;
                               scores += sd.TotalScores;
                               d.Answer = sd.Answer;
                           }
                       }
                   }

                   test.ObjectiveScores = scores;

                   context.SaveChanges();
               }
        }

       
    }

    internal class StuAns
    {
        public string Name { get; set; }
                                                                                              
    }
}



